/* eslint-disable no-case-declarations */
import React, { Component } from 'react';
import PropTypes from 'prop-types';
import { connect } from 'react-redux';
import { bindActionCreators } from 'redux';
import { Button, Balloon } from '@teamix/ui';
import Pagination from 'components/commonPagination';
import {
  Header,
  Body,
  BodyContent,
  Content,
  YunxiaoIcon,
  ButtonIcon,
  YunxiaoTable,
  Title,
} from '@alife/devops-ui';
import { enterPage, Perf } from 'utils/track';
import { ENUM, ORGANIZATION_ADMIN_ROLES } from 'utils/constants.js';
import { access } from 'components/accessContainer/util';
import * as actions from '../actions/index';
import utils from 'utils';
import ListLoading from 'atComponents/ListLoading';
import ListEmpty from 'atComponents/ListEmpty';
import dayjs from 'dayjs';
import RecoverModal from './recoverModal';
import docs from 'utils/docs';
import intl from '../../../../../../../locale';

class Root extends Component {
  static propTypes = {
    currentPage: PropTypes.number,
    isLoadingTable: PropTypes.string,
    tableData: PropTypes.arrayOf(PropTypes.object),
    getTrashes: PropTypes.func,
    total: PropTypes.number,
  };

  state = {
    isModalOpen: false,
    modalData: null,
    pageSize: 10,
  };

  componentDidMount() {
    document.title = intl.get({
      id: 'code-assets.trashes.containers.root.YunxiaoCodeupEnterpriseCodeManagement',
      defaultMessage: '云效 Codeup · 企业级代码管理平台',
    });
    this.props.getTrashes(1);

    enterPage('Organization-trashes', {
      sendPerf: false,
    });
  }

  componentWillUnmount() {
    this.props.resetData();
  }

  onPageNoChange = (page) => {
    const { pageSize } = this.state;
    this.props.getTrashes(page, pageSize);
  };

  onPageSizeChange = (pageSize) => {
    this.props.getTrashes(1, pageSize);
    this.setState({
      pageSize,
    });
  };

  renderOperator = (value) => {
    const user = value.name || value.username;
    return (
      <Title align="t" trigger={<span>{user}</span>}>
        <div>{user}</div>
      </Title>
    );
  };

  renderTime = (value) => {
    return utils.getBeautyTime(value);
  };

  renderAction = (value, index, record) => {
    // access_level >=40 即拥有master组件
    if (!record.resource) {
      return null;
    }
    const { access_level } = record.resource;
    const { user_role } = window.FORCE.organization;
    const hasAccess =
      access(ORGANIZATION_ADMIN_ROLES, user_role) || access_level >= ENUM.access_level_id.MASTER;
    return (
      <Balloon.Tooltip
        align="t"
        trigger={
          <Button
            type="primary"
            text
            disabled={!hasAccess}
            onClick={() => {
              if (!hasAccess) {
                return;
              }
              this.setState({
                modalData: record,
                isModalOpen: true,
              });
            }}
          >
            {intl.get({
              id: 'code-assets.trashes.containers.root.Recovery',
              defaultMessage: '恢复',
            })}
          </Button>
        }
      >
        {hasAccess
          ? intl.get({
              id: 'code-assets.trashes.containers.root.RestoreContent',
              defaultMessage: '恢复内容',
            })
          : intl.get({
              id: 'code-assets.trashes.containers.root.YouAreNotAuthorizedTo',
              defaultMessage: '无恢复权限，请联系管理员操作',
            })}
      </Balloon.Tooltip>
    );
  };

  renderName = (value, index, record) => {
    const { source_type, resource } = record;
    const isGroup = source_type === 'Namespace';
    const repoIcon = (
      <Balloon.Tooltip align="t" trigger={<YunxiaoIcon type="code-basement-line" />}>
        {intl.get({ id: 'code-assets.trashes.containers.root.CodeBase', defaultMessage: '代码库' })}
      </Balloon.Tooltip>
    );

    const groupIcon = (
      <Balloon.Tooltip align="t" trigger={<YunxiaoIcon type="folder-line" />}>
        {intl.get({
          id: 'code-assets.trashes.containers.root.CodeGroup',
          defaultMessage: '代码组',
        })}
      </Balloon.Tooltip>
    );

    const name = resource.name_with_namespace;

    return (
      <div className="trash-resource-name">
        <span className="trash-mr12">{isGroup ? groupIcon : repoIcon}</span>
        <Title align="t" trigger={<span className="trash-mr12">{name}</span>}>
          {name}
        </Title>
        {isGroup && [
          <Balloon.Tooltip
            align="t"
            trigger={
              <div style={{ width: 60 }}>
                <Button type="normal" text className="normal-color-btn">
                  <YunxiaoIcon type="folder-line" /> {resource.group_count}
                </Button>
              </div>
            }
          >
            {intl.get({
              id: 'code-assets.trashes.containers.root.SubcodeGroup',
              defaultMessage: '子代码组',
            })}
          </Balloon.Tooltip>,
          <Balloon.Tooltip
            align="t"
            trigger={
              <div style={{ width: 60 }}>
                <Button type="normal" text className="normal-color-btn">
                  <YunxiaoIcon type="code-basement-line" /> {resource.project_count}
                </Button>
              </div>
            }
          >
            {intl.get({
              id: 'code-assets.trashes.containers.root.CodeBase',
              defaultMessage: '代码库',
            })}
          </Balloon.Tooltip>,
        ]}
      </div>
    );
  };

  renderDay = (value) => {
    const now = dayjs().valueOf();
    const time = dayjs(value).valueOf();
    const day = (time - now) / 1000 / 60 / 60 / 24;
    if (day < 0) {
      return intl.get({
        id: 'code-assets.trashes.containers.root.Expired',
        defaultMessage: '已过期',
      });
    } else if (day < 1) {
      return intl.get({ id: 'code-assets.trashes.containers.root.Day', defaultMessage: '< 1 天' });
    } else {
      const dayNum = Math.floor(day);
      return intl.get(
        {
          id: 'code-assets.trashes.containers.root.DaynumDays',
          defaultMessage: '{dayNum} 天',
        },
        { dayNum },
      );
    }
  };
  renderTable = () => {
    const { tableData, isLoadingTable, total, tableDataFetched } = this.props;
    if (isLoadingTable && !tableDataFetched) {
      return <ListLoading />;
    }
    if (!isLoadingTable && tableDataFetched && total === 0) {
      return (
        <>
          <Perf page="Organization-trashes" />
          <ListEmpty
            fullPage
            type="org"
            content="回收站非常干净"
            description={intl.get({
              id: 'code-assets.trashes.containers.root.RecycleBinAvoidAccidentalDeletion',
              defaultMessage: '回收站避免误删数据，支持有效期内一键恢复资源',
            })}
            image="none"
            btns={[]}
          />
        </>
      );
    }
    return (
      <div className="trash-container">
        <Perf page="Organization-trashes" />
        <div>
          <YunxiaoTable
            hasBorder={false}
            dataSource={tableData}
            loading={isLoadingTable}
            className="trash-table"
            emptyContent={
              <ListEmpty
                content={intl.get({
                  id: 'code-assets.trashes.containers.root.NoData',
                  defaultMessage: '暂无数据',
                })}
                imgType="search"
                className="table-list-empty"
              />
            }
          >
            <YunxiaoTable.Column
              title="库/组名称"
              className="trash-name-col"
              dataIndex="resource"
              cell={this.renderName}
            />

            <YunxiaoTable.Column
              title={intl.get({
                id: 'code-assets.trashes.containers.root.DeleteOperator',
                defaultMessage: '删除操作人',
              })}
              className="trash-operator-col"
              dataIndex="recycled_by"
              cell={this.renderOperator}
            />

            <YunxiaoTable.Column
              title={intl.get({
                id: 'code-assets.trashes.containers.root.DeleteTime',
                defaultMessage: '删除时间',
              })}
              dataIndex="recycled_at"
              cell={this.renderTime}
            />

            <YunxiaoTable.Column
              title={intl.get({
                id: 'code-assets.trashes.containers.root.RemainingTime',
                defaultMessage: '剩余时间',
              })}
              dataIndex="expires_at"
              cell={this.renderDay}
            />
            <YunxiaoTable.Column
              title={intl.get({
                id: 'code-assets.trashes.containers.root.Operation',
                defaultMessage: '操作',
              })}
              dataIndex="action_type"
              className="trash-action-col"
              cell={this.renderAction}
            />
          </YunxiaoTable>
        </div>
      </div>
    );
  };

  render() {
    const { isModalOpen, modalData } = this.state;
    const { currentPage, total } = this.props;
    return (
      <>
        <Header
          title={
            <>
              {intl.get({
                id: 'code-assets.trashes.containers.root.RecycleBin',
                defaultMessage: '回收站',
              })}
              <Balloon
                trigger={
                  <ButtonIcon
                    name="question-line"
                    text
                    style={{ marginLeft: 8, display: 'flex', alignItems: 'center' }}
                  />
                }
                closable={false}
              >
                {intl.get({
                  id: 'code-assets.trashes.containers.root.OnlyTheDataOfThe',
                  defaultMessage: '仅保留最近 15 天的数据，超期将自动彻底删除。',
                })}
                <a href={docs('trash')} target="_blank" rel="noreferrer">
                  {intl.get({
                    id: 'code-assets.trashes.containers.root.HowDoIUseThe',
                    defaultMessage: '如何使用回收站？',
                  })}
                </a>
              </Balloon>
            </>
          }
        />
        <Body>
          <BodyContent>
            <Content>{this.renderTable()}</Content>
            <Pagination
              onChange={this.onPageNoChange}
              pageSize={this.state.pageSize}
              onPageSizeChange={this.onPageSizeChange}
              current={currentPage}
              total={total}
            />
          </BodyContent>
        </Body>

        {isModalOpen && (
          <RecoverModal
            closeModal={(needReq) => {
              this.setState({
                isModalOpen: false,
                modalData: null,
              });

              needReq && this.props.getTrashes(1);
            }}
            isModalOpen={isModalOpen}
            record={modalData}
          />
        )}
      </>
    );
  }
}

export default connect(
  (state) => state.organization.trashes,
  (dispatch) => bindActionCreators(actions, dispatch),
)(Root);
